package com.ws.universal.tools.adapter;


import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import java.util.List;

/**
 * 相对于页面较多，且动态添加删除时 调用
 */
public class LiveViewPagerFragmentStatePagerAdapter extends FragmentStatePagerAdapter {

    private List<Fragment> mFragmentList;


    public LiveViewPagerFragmentStatePagerAdapter(@NonNull FragmentManager fm, int i) {
        super(fm, i);

    }

    public List<Fragment> getmFragmentList() {
        return mFragmentList;
    }

    public void setFragmentList(List<Fragment> mFragmentList) {

        this.mFragmentList = mFragmentList;
        notifyDataSetChanged();
    }

//    public List<Fragment> getmFragmentList() {
//        return mFragmentList;
//    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        // 新建一个Fragment来展示ViewPager item的内容，并传递参数 //%mFragmentList.size() 无限循环 size需大于3 不然会报错
//        if (mFragmentList.size() > 1) {
//            return mFragmentList.get(position % mFragmentList.size());
//        } else {
//            return mFragmentList.get(position);
//        }
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        if (mFragmentList != null) {
//            if (mFragmentList.size() > 1) {
//                return Integer.MAX_VALUE; //无限循环 size需大于3 不然会报错
//            } else {
//                return mFragmentList.size(); //不无限循环
//            }
            return mFragmentList.size(); //不无限循环
        } else {
            return 0;
        }

    }

    // 解決 Android NullPointerException FragmentHostCallback.getHandler()
/*    @Override
    public void finishUpdate(@NonNull ViewGroup container) {
        try {
            super.finishUpdate(container);
        } catch (NullPointerException nullPointerException) {
            LogcatUtils.e("", "Catch the NullPointerException in FragmentPagerAdapter.finishUpdate");
        }

    }*/
}
